package com.itheima.sh.a_axios_json_01;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

@WebServlet("/json3Servlet")
public class Json3Servlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //获取请求参数
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            //输出控制台
            System.out.println(username+"----"+password);
            //创建friden集合对象
            ArrayList<Friend> friends = new ArrayList<>();
            Collections.addAll(friends,new Friend("001","张三",123),new Friend("002","李四",456)
            ,new Friend("003","王五",789));
            //执行到这里说明没有异常，响应给前端
            Result result = new Result(true, "响应好友列表成功", friends);
            //将result转化为json对象
            String resultJson = JSON.toJSONString(result);
            //将result响应给前端浏览器
            response.getWriter().print(resultJson);
        } catch (Exception e) {
            //将异常打印到控制台
            e.printStackTrace();
            //执行到这里说明出现异常
            Result result = new Result(false, "查询好友列表失败");
            //将result转化为json对象
            String strJson = JSON.toJSONString(result);
            //将result响应给浏览器
            response.getWriter().print(strJson);
        }
    }
}